<!-- 获取登录用户所有商品 -->
<template>
    <div>  
        <div class="view-toggle">
            <el-button-group>
                <el-button :type="viewMode === 'table' ? 'primary' : ''"  @click="viewMode = 'table'"title="表格视图">
                    <el-icon><Grid /></el-icon>
                </el-button>
                <el-button :type="viewMode === 'card' ? 'primary' : ''"@click="viewMode = 'card'"title="卡片视图">
                    <el-icon><Menu /></el-icon>
                </el-button>
            </el-button-group>
        </div>
        <!-- 表格视图 -->
            <el-table v-if="viewMode === 'table'" :data="GoodsArr" v-loading="loading"style="width: 100%" empty-text="暂无商品">
                <el-table-column prop="name" label="商品名称" width="120" />
                <el-table-column prop="recommend" label="商品介绍" width="120" />
                <el-table-column prop="price" label="价格" width="120">
                    <template #default="{ row }">
                        {{ row.price/100 }} 元
                    </template>
                </el-table-column>
                <el-table-column prop="uid" label="卖家ID" width="120" />
                <el-table-column prop="endTime" label="下架时间">
                    <template #default="{ row }">
                        {{ formatTime(row.endTime) }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="120">
                    <template #default="{ row }">
                        <el-button class="buy-btn" v-if = "row.isPut" @click="unShopArr(row.id)">下架喵</el-button>
                        <el-button class="buy-btn" v-else @click="upShopArr(row.id)">上架喵</el-button>
                    </template>
                </el-table-column>
            </el-table>
        <!-- 卡片视图 -->
        <div v-else v-loading="loading" class="card-list goods-container">
            <el-empty v-if="!GoodsArr.length && !loading" description="暂无商品" />
            <el-row :gutter="20">
                <el-col v-for="(item, index) in GoodsArr" :key="index":xs="24" :sm="12" :md="8" :lg="4" class="card-col" >
                    <el-card class="goods-card">

                        <!-- 商品信息 -->
                        <div class="goods-info">
                        <div class="title-price">
                            <h3 class="name">{{ item.name }}</h3>
                            <span class="price">{{ item.price/100 }} 元</span>
                        </div>

                        <div class="meta-info">
                            <p class="recommend">{{ item.recommend }}</p>
                            <p class="seller">卖家ID: {{ item.uid }}</p>
                            <p class="end-time">下架时间: {{ formatTime(item.endTime) }}</p>
                        </div>
                        <el-button class="buy-btn" v-if = "item.isPut" @click="unShopArr(item.id)">下架喵</el-button>
                        <el-button class="buy-btn" v-else @click="upShopArr(item.id)">上架喵</el-button>
                        </div>
                    </el-card>
                </el-col>
            </el-row>
        </div>
    </div>  
</template>
  
<script setup>
    import { ref, onMounted} from 'vue'
    import { ElTable, ElTableColumn, ElMessage} from 'element-plus'
    import { Grid, Menu } from '@element-plus/icons-vue'
    import { useStore } from 'vuex';
    import * as contract from '../../test/Truffle-ABI.js'
    import axios from 'axios';
    import { useRouter } from 'vue-router'

    const loading = ref(false)
    const GoodsArr = ref([])
    const viewMode = ref('card')
    const store = useStore()
    const router = useRouter()
    //上架商品
    function upShopArr(GoodsID) {
        store.commit('setTxt','上架商品')
        store.commit('updateUpGoodsID',GoodsID)
        router.push('/addGoodsArr')
    }
    //下架商品
    const unShopArr = async(GoodsID)=>{
        try{
            await contract.deleteGoodsArray(GoodsID)
            ElMessage.success('下架成功喵')
            fetchGoods()
        }catch(error){
            ElMessage.error('下架失败喵')
        }
        
    }

    // 格式化时间方法
    const formatTime = (timestamp) => {
        if (!timestamp) return '未上架喵'
        const date = new Date(timestamp/1000)
        return `${date.toLocaleDateString()} ${date.toLocaleTimeString()}`
    }
  
  
  // 获取商品数据
    const fetchGoods = async () => {
        try {
            loading.value = true
            GoodsArr.value = []
            await contract.initWeb3()
            const data =  await contract.getUserGoods(store.state.user.uid)
            console.log('获取区块链数据成功:', data)
            for (let i = 0; i < data.length; i++) {
                try {
                    const response = await axios.get(`http://localhost:3001/api/data/${data[i].id}`)
                    console.log('获取数据库商品成功:', response.data)
                    const Goods = {
                        id:data[i].id,
                        uid: data[i].seller,
                        name: response.data.name,
                        recommend: response.data.recommend,
                        price: data[i].price,
                        endTime: data[i].endTime,
                        isPut:data[i].isPut
                    }
                    console.log('获取:', Goods)
                    GoodsArr.value.push(Goods)
                } catch (innerError) {
                    console.error(`商品${data[i].id}详情获取失败:`, innerError)
                }
            }
        } catch (error) {
            console.error(error)
        } finally {
            loading.value = false
        }
    }
  
    onMounted(() => {
        fetchGoods()
    })
</script>
  
<style scoped>
    
    .goods-containerTable {
        position: relative; /* 确保伪元素定位正确 */
        
    }
    
    .card-list {
        padding: 20px;
    }

    .card-col {
        margin-bottom: 20px;
    }

    .goods-card {
        height: 100%;
        transition: transform 0.3s;
    }

    .goods-card:hover {
        transform: translateY(-5px);
    }

    .goods-image {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
    }

    .goods-info {
        padding: 15px;
    }

    .title-price {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 12px;
    }

    .name {
        margin: 0;
        font-size: 16px;
        color: #303133;
    }

    .price {
        font-size: 18px;
        color: #f56c6c;
        font-weight: bold;
    }

    .meta-info {
        margin: 12px 0;
        font-size: 12px;
        color: #909399;
    }

    .meta-info p {
        margin: 6px 0;
    }

    .buy-btn {
        width: 100%;
        margin-top: 10px;
    }

    .view-toggle {
        margin-bottom: 20px;
        display: flex;
        justify-content: flex-end;
    }

    .el-button-group {
        border-radius: 4px;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }

    .el-button {
        padding: 10px 15px;
        transition: all 0.3s;
    }
    
    .el-button:not(.is-primary) {
        background: #fff;
        border-color: #dcdfe6;
    }

    .el-button + .el-button {
        margin-left: -1px;
    }

    .el-icon {
        font-size: 18px;
    }
</style>